package com.primeton.fbsearch.xls;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;

import com.primeton.fbsearch.framework.DocumentHandler;
import com.primeton.fbsearch.framework.DocumentHandlerException;
 
public class POIExcelHandler implements DocumentHandler {
	
	 public Document getDocument(InputStream is)    throws DocumentHandlerException {
 
		String content = null;
		StringBuffer sb = new StringBuffer();
		try {
			//InputStream is = new FileInputStream(new File(file));
			/*
			HSSFWorkbook workbook = new HSSFWorkbook(is);
			for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
				sb.append(workbook.getSheetName(i));
				sb.append("\n");
				HSSFSheet sheet = workbook.getSheet(workbook.getSheetName(i));
				for (int j = 0; j <= sheet.getLastRowNum(); j++) {
					HSSFRow row = sheet.getRow(j);
					if (row != null) {
						for (int k = 0; k <= row.getLastCellNum(); k++) {
							HSSFCell cell = row.getCell((short) k);
							if (cell != null) {
//								if (cell.getRichStringCellValue() != null
//										&& !cell.getRichStringCellValue().equals(""))
//									sb.append(cell.getRichStringCellValue());
								int type = cell.getCellType();
								switch(type) {
								case HSSFCell.CELL_TYPE_NUMERIC:
									sb.append(cell.getNumericCellValue());
									break;
								case HSSFCell.CELL_TYPE_STRING:
								case HSSFCell.CELL_TYPE_FORMULA:
								case HSSFCell.CELL_TYPE_BOOLEAN:
								case HSSFCell.CELL_TYPE_ERROR:
									//sb.append(cell.getRichStringCellValue());
									sb.append(cell.getStringCellValue());
									
									break;
								}
								sb.append("\t");
							}
						}
						sb.append("\n");
					}
				}
			}
			*/
			content = sb.toString();
		} catch (Exception e) {
			throw new DocumentHandlerException(
					"Cannot extract text from a xls document", e);
		}
	    Document doc = new Document();
		if (content.length() > 0) {
			//return content;
		      doc.add(new Field("body", content,Field.Store.YES, Field.Index.TOKENIZED,	Field.TermVector.WITH_POSITIONS_OFFSETS));	
 
		      if(content != null && content.length()>20){
		    	  String tmp = content.substring(0,20);
		    	  System.out.println("POIExcelHandler="+tmp);
		      }
		      
		      return doc;
		}
		return null;
	}
	 public static void main(String[] argv) throws Exception
	 {
		 POIExcelHandler handler = new POIExcelHandler();
		 String file = "D:\\OpenSource\\search_data\\申请书.xls";
 		InputStream is = new FileInputStream(new File(file));
		 handler.getDocument(is);
		 
		 
	 }	 

}
